package com.wcl.demo.ui.activity;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.wcl.demo.R;
import com.wcl.demo.model.entity.BackGroundData;
import com.wcl.demo.model.entity.RecommendSoftData;
import com.wcl.demo.network.VolleySingleton;
import com.wcl.demo.ui.activity.iteminterface.OnDownLoadClickListener;
import com.wcl.demo.ui.adapter.BackgroundDownLoadAdapter;
import com.wcl.demo.utils.DialogUtils;
import com.wcl.demo.utils.OkHttpClientManager;
import com.wcl.demo.utils.ProgressUtils;
import com.wcl.demo.view.CustomDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/12/7.
 */
public class BachgroundDownloadActivity extends BaseActivity implements OnDownLoadClickListener {
    private RecyclerView download_recyvlerView;//定义RecyclerView
    private final static String TAG = "RecommendSoftActivity";
    private BackgroundDownLoadAdapter adapter;//定义背景下载的适配器
    private ImageView activity_set_bac_Iv;//定义返回按钮
    //加载布局
    @Override
    protected int getLayout() {
        return R.layout.activity_background_download;
    }
    //初始化控件
    @Override
    protected void initView() {
        download_recyvlerView = (RecyclerView) findViewById(R.id.download_recyvlerView);
        activity_set_bac_Iv = (ImageView) findViewById(R.id.activity_set_bac_Iv);
    }
    //初始化数据
    @Override
    protected void initData() {
        GridLayoutManager manager = new GridLayoutManager(this, 1);//定义布局管理器
        adapter = new BackgroundDownLoadAdapter();//初始化适配器
        download_recyvlerView.setLayoutManager(manager);//recyclerView加载布局管理器
        download_recyvlerView.setAdapter(adapter);//recyclerView加载适配器
        adapter.setOnDownLoadClickListener(this);//适配器回调监听
        requestSoft();//请求网络数据
    }

    /***
     * 下载监听
     *
     * @param progressBar 从适配器里面传过来的进度条
     * @param url         下载的网址
     */
    @Override
    public void onDownloadClick(ProgressBar progressBar, String url) {
        downLoad(url, progressBar);
    }

    /***
     * 请求网络数据
     */
    private void requestSoft() {
        String url = "http://106.38.184.107/api/search/all?q=%E5%A3%81%E7%BA%B8&src=ms_" +
                "zhushou&inp=%E5%A3%81%E7%BA%B8&hfrom=&hidetab=&v2=1&ext_filter=3&os=18&s_3pk=1" +
                "&pq=%E5%A3%81%E7%BA%B8&page=1&fm=home_5_6_ssall&m=5284047f4ffb4e04824a2fd1d1f0cd62&" +
                "s_stream_app=1&m2=990b9fd70e861373134f9a5e44f89c1c&v=3.2.57&re=10005&nt=1&ch=710048&" +
                "model=Motorola+Moto+X+-+4.3+-+API+18+-+720x1280&sn=4.330415746098476&cu=&ca1=x86&" +
                "ca2=armeabi-v7a&ppi=720x1184&cpc=1&startCount=49&snt=-1&timestamp=1449486996181";
        JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            Gson gson = new Gson();
            List<RecommendSoftData> list = new ArrayList<>();

            @Override
            public void onResponse(JSONObject response) {
                if (response != null && response.has("data")) {
                    try {
                        JSONObject object = response.getJSONObject("data");
                        if (object.has("app")) {
                            JSONObject object1 = object.getJSONObject("app");
                            if (object1.has("data")) {
                                JSONArray array = object1.getJSONArray("data");
                                for (int i = 0; i < array.length(); i++) {
                                    String str = array.getString(i);
                                    RecommendSoftData data = gson.fromJson(str, RecommendSoftData.class);
                                    list.add(data);
                                    Log.i("searchhimlog", data + "");
                                }
                                adapter.addData(list);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return super.getHeaders();
            }
        };
        VolleySingleton.getInstance().addRequest(request, TAG);//将请求添加到队列中
    }


    /**
     * 下载软件
     *
     * @param url         软件地址
     * @param progressBar 显示的进度条
     */
    private void downLoad(String url, final ProgressBar progressBar) {
        Log.i("taggg", url);
        OkHttpClientManager.downloadAsyn(url, "sdcard/cache/", new OkHttpClientManager.ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        Log.d("TAGGG", "ERROR" + e);
                    }

                    @Override
                    public void onResponse(String response) {
                        Log.d("TAGGG", "路径:--->" + response);
                    }

                    @Override
                    public void inprogress(float progress) {
                        progressBar.setProgress((int) (100 * progress));
                    }
                }
        );
    }
}
